package com.zklh.leetcode.tree.middle;

import com.zklh.leetcode.tree.model.TreeNode;

/**
 * @author ：tong nan
 * @date ：Created in 2021/5/11 18:12
 * @description ：用于检查是否是合法的二叉搜索树
 * @modifiedBy ：
 */
public class BSTValidityChecker {



    public boolean check(TreeNode root) {
        return check(root, null, null);
    }


    public boolean check(TreeNode root, TreeNode min, TreeNode max) {

        if (root == null) {
            return true;
        }
        boolean result = true;

        if (min != null && min.val > root.val ) {
            result &= false;
        }

        if (max != null && max.val < root.val) {
            result &=false;
        }

        return result && check(root.left, min, root) && check(root.right, root, max);

    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(10);
        root.left = new TreeNode(5);
        root.right = new TreeNode(15);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(20);

        BSTValidityChecker checker = new BSTValidityChecker();
        System.out.println(checker.check(root));
    }


}
